package com.zxx.coolweather._wuguan2;

import com.alibaba.fastjson.JSON;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.StringRequest;

/**
 * 解析所有JavaBean的自定义请求
 *
 * @author zxx on 2022/1/12
 */
public class RequestJavaBean<E> extends Request<E> {

    private Class<E> clazz;

    public RequestJavaBean(String url, Class<E> clazz) {
        super(url);
        this.clazz = clazz;
    }

    public RequestJavaBean(String url, RequestMethod requestMethod, Class<E> clazz) {
        super(url, requestMethod);
        this.clazz = clazz;
    }

    @Override
    public E parseResponse(Headers responseHeaders, byte[] responseBody) throws Exception {
        String result = StringRequest.parseResponseString(responseHeaders, responseBody);
        try {
            return JSON.parseObject(result, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            E instance = null;
            try {
                // 但是前提是传进来的JavaBean必须提供了默认实现
                instance = clazz.newInstance();
            } catch (InstantiationException | IllegalAccessException e1) {
            }
            return instance;
        }
    }


}
